package study.springboot.starter.tacker.rest;

import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import study.springboot.starter.tacker.Headers;
import study.springboot.starter.tacker.TrackerKeys;

import java.io.IOException;
import java.net.URI;
import java.util.concurrent.TimeUnit;

@Slf4j
public class RestHeaderInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body,
                                        ClientHttpRequestExecution execution) throws IOException {
        //设置头部
        HttpHeaders headers = request.getHeaders();
        headers.add(Headers.X_REQUEST_ID, TrackerKeys.get());
        //计算耗时
        Stopwatch stopwatch = Stopwatch.createStarted();
        URI uri = request.getURI();
        //请求并返回
        ClientHttpResponse response;
        try {
            response = execution.execute(request, body);
        } finally {
            log.info("url {} cost time [{} ms]", uri.toString(), stopwatch.elapsed(TimeUnit.MILLISECONDS));
        }
        return response;
    }
}
